package cn.pzhu.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
	private static String driver=null;
	private static String url=null;
	private static String user=null;
	private static String password=null;
	//加载时,运行一次
	static {
		InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
		Properties pro = new Properties();
		try {
			pro.load(is);
			driver = pro.getProperty("driver");
			url = pro.getProperty("url");
			user = pro.getProperty("user");
			password = pro.getProperty("password");
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println(driver);
		System.out.println(url);
		System.out.println(user);
		System.out.println(password);
	}
	
	public static Connection getConnection() {
		Connection con = null;
		try {
			con = DriverManager.getConnection(url,user,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("CON "+con);
		return con;
	}
	public static void Close(Connection con,Statement sta,ResultSet res) {
		try {
			if(res!=null) {
				res.close();				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(sta!=null) {
				sta.close();				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(con!=null) {
				con.close();				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static void Close(Connection con,Statement sta) {
		Close(con,sta,null);
	}
	public static void Close(Connection con,PreparedStatement sta,ResultSet res) {
		Close(con,(Statement)sta,res);
	}
	public static void Close(Connection con,PreparedStatement sta) {
		Close(con,(Statement)sta,null);
	}
}
